﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace P2PChat.Log
{
    /// <summary>
    /// 提供基于时间戳的日志文件的实现
    /// </summary>
    public class TimeStampLog : ILog
    {
        /// <summary>
        /// 日志文件的路径，不需要带有扩展名
        /// </summary>
        private string filePath;
        /// <summary>
        /// 获取日志文件的路径
        /// </summary>
        public string FilePath
        {
            get
            {
                return filePath;
            }
            set
            {
                filePath = value;
            }
        }

        /// <summary>
        /// 表示日志条目
        /// </summary>
        private struct __LogEntry
        {
            public DateTime time;
            public String content;
        }
        /// <summary>
        /// 日志条目缓存
        /// </summary>
        private List<__LogEntry> entries = new List<__LogEntry>();


        /// <summary>
        /// 将日志文件写入路径
        /// </summary>
        public void Write()
        {
            // 写入文件
            FileInfo file = new FileInfo(this.FilePath);

            try
            {
                FileStream fs = file.Open(FileMode.Append, FileAccess.Write);
                StreamWriter writer = new StreamWriter(fs);

                foreach (__LogEntry ent in entries)
                {
                    writer.WriteLine("{0} - {1}",
                        ent.time.ToLongTimeString(),
                        ent.content);
                }
            }
            catch (NotSupportedException ex)
            {
                throw new NotSupportedException(ex.Message + ":" + this.FilePath);
            }

            // 清除日志条目缓存
            entries.Clear();
        }

        /// <summary>
        /// 添加一条日志条目
        /// </summary>
        /// <param name="logContent">日志的内容，每个参数对应一个条目</param>
        public void Add(params string[] logContent)
        {
            for (int i = 0; i < logContent.Length; i++)
            {
                __LogEntry newEntry = new __LogEntry();
                newEntry.time = DateTime.Now;
                newEntry.content = logContent[i];
                entries.Add(newEntry);
            }
        }
    }
}
